package com.tarena.lbs.business.servcie.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tarena.lbs.base.protocol.pager.PageResult;
import com.tarena.lbs.business.dao.mapper.StoreMapper;
import com.tarena.lbs.business.pojo.po.StorePO;
import com.tarena.lbs.business.pojo.query.AreaStoreQuery;
import com.tarena.lbs.business.pojo.query.StoreQuery;
import com.tarena.lbs.business.pojo.vo.StoreVO;
import com.tarena.lbs.business.servcie.StoreService;
import com.tarena.lbs.user.api.UserApi;
import com.tarena.lbs.user.api.pojo.dto.AdminDto;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class StoreServiceImpl implements StoreService {
    @Autowired
    private StoreMapper storeMapper;
    @DubboReference
    private UserApi userApi;
    @Override
    public PageResult<StoreVO> selectStore(StoreQuery query) {
    //com.baomidou.mybatisplus.extension.plugins.pagination.
        Page<StorePO> page = new Page<>(query.getPageNo(),query.getPageSize());
        QueryWrapper<StorePO> queryWrapper = generatePOQuery(query);
        log.debug("业务层前端传来pageNo:{}和PageSize:{}", query.getPageNo(), query.getPageSize());
        log.info("业务层queryWrapper:{}", queryWrapper.toString());
        Page<StorePO> resultPage = storeMapper.selectPage(page, queryWrapper);
        List<StoreVO> storeVOS = convertPoListToVoList(resultPage.getRecords());
        PageResult<StoreVO> pageResult = new PageResult<>();
        pageResult.setObjects(storeVOS);
        pageResult.setTotal(resultPage.getTotal());  // 使用实际查询的总数
        pageResult.setPageNo(query.getPageNo());
        pageResult.setPageSize(query.getPageSize());
        log.debug("业务层List storeVOS:{}", storeVOS);
        return pageResult;
    }

    @Override
    public PageResult<StoreVO> selectStoreByAreaAndBusinessId(AreaStoreQuery query, Integer businessId) {
        int rows=storeMapper.selectByParenId(query);
        log.info("前端传来的是否有省级rows:{}",rows);
        Page<StorePO> page = new Page<>(query.getPageNo(),query.getPageSize());
        QueryWrapper<StorePO> queryWrapper = generatePOQueryByArea(query,businessId,rows);
        log.debug("业务层前端传来pageNo:{}和PageSize:{}", query.getPageNo(), query.getPageSize());
        log.debug("业务层queryWrapper:{}", queryWrapper);
        log.info("前端的数组:{}",query);
        Page<StorePO> resultPage = storeMapper.selectPage(page, queryWrapper);
        List<StoreVO> storeVOS = convertPoListToVoList(resultPage.getRecords());
        log.info("storeVOS:{}",storeVOS);
        PageResult<StoreVO> pageResult = new PageResult<>();
        pageResult.setObjects(storeVOS);
        pageResult.setTotal(resultPage.getTotal());  // 使用实际查询的总数
        pageResult.setPageNo(query.getPageNo());
        pageResult.setPageSize(query.getPageSize());
        log.debug("业务层List storeVOS:{}", storeVOS);
        return pageResult;
    }

    private QueryWrapper<StorePO> generatePOQueryByArea(AreaStoreQuery query, Integer businessId,int rows) {
        QueryWrapper<StorePO> queryWrapper = new QueryWrapper<>();
        //当前用户id
        Integer userId = getUserIdFromHeader();
        log.debug("登录人userId:{}",userId);
        AdminDto dto =userApi.getAdminById(userId);
        //当前商家的id
        log.debug("当前登陆人商家id:{}",businessId);
        log.debug("当前登录人id:{},信息:{}",userId,dto);
        queryWrapper.eq("business_id",businessId);
        List<Long>list=query.getCityIdList();
        log.info("方法当中的数组:{}",list);
        log.info("方法当中的rows:{}",rows);
        if (list!=null&&rows>0){
            queryWrapper.in("province_id", list)
                    .or()
                    .in("city_id", list)
                    .or()
                    .in("area_id", list);
        }
        else {
            queryWrapper.in("city_id",list);
        }
            log.debug("业务层商家businessid:{]",businessId);
        return queryWrapper;
    }

    private List<StoreVO> convertPoListToVoList(List<StorePO> records) {
        if (records == null) {
            return new ArrayList<>();
        }
        return records.stream()
                .map(po -> {
                    StoreVO vo = new StoreVO();
                    BeanUtils.copyProperties(po, vo);
                    return vo;
                })
                .collect(Collectors.toList());
    }

    private QueryWrapper<StorePO> generatePOQuery(StoreQuery query) {
        QueryWrapper<StorePO> queryWrapper = new QueryWrapper<>();
        //当前用户id
        Integer userId = getUserIdFromHeader();
        log.debug("登录人userId:{}",userId);
        AdminDto dto =userApi.getAdminById(userId);
        //当前商家的id
        Integer businessId=dto.getBusinessId();
        log.debug("当前登陆人商家id:{}",businessId);
        log.debug("当前登录人id:{},信息:{}",userId,dto);
        queryWrapper.eq("business_id",businessId);
        if (query != null) {
            if (query.getProvinceId() != null) {
                queryWrapper.eq("Province_id", query.getProvinceId());
            }
            if (query.getCityId() != null) {
                queryWrapper.eq("city_id", query.getCityId());
            }
            if (StringUtils.isNotBlank(query.getStoreHeadPhone())) {
                queryWrapper.like("Store_head_phone", query.getStoreHeadPhone());
            }
            // 状态查询
            log.debug("业务层商家businessid:{]",businessId);
        }
        return queryWrapper;
    }
    private Integer getUserIdFromHeader() {
        try {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (attributes == null) return null;
            HttpServletRequest request = attributes.getRequest();
            String token = request.getHeader("authorization");
            log.debug("tokenn:{}",token);
            if (StringUtils.isNotBlank(token)) {
                Integer number=parseUserIdFromToken(token);
                log.debug("用户number:{}",number);
                return number;
            }
            return null;
        } catch (Exception e) {
            log.error("从请求头获取用户ID失败", e);
            return null;
        }
    }
    private Integer parseUserIdFromToken(String token) {
        try {
            // JWT token 由三部分组成，用点分隔：Header.Payload.Signature
            String[] parts = token.split("\\.");
            if (parts.length != 3) {
                log.warn("JWT token 格式不正确");
                return null;
            }
            // 解码 Payload 部分 (Base64Url)
            String payload = new String(Base64.getUrlDecoder().decode(parts[1]), StandardCharsets.UTF_8);
            // 解析 JSON payload
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode payloadNode = objectMapper.readTree(payload);
            // 根据你的 JWT 结构获取用户ID
            // 从你的 token 看，payload 包含一个 payload 字段，里面是用户信息
            if (payloadNode.has("payload")) {
                String innerPayload = payloadNode.get("payload").asText();
                JsonNode userInfo = objectMapper.readTree(innerPayload);

                if (userInfo.has("id")) {
                    return userInfo.get("id").asInt();
                }
            }
            // 或者直接查找 id 字段
            if (payloadNode.has("id")) {
                return payloadNode.get("id").asInt();
            }
            log.warn("在 JWT token 中未找到用户ID");
            return null;
        } catch (Exception e) {
            log.error("解析 JWT token 失败", e);
            return null;
        }
    }
}
